<template>
  <a-modal
    v-model:open="open"
    title="编辑任务"
    @close="closes"
    @ok="handleSubmit"
    :width="800"
  >
    <a-form :model="formState" layout="horizontal" :label-col="{ style: { minWidth: '80px', textAlign: 'left' } }">
      <a-form-item label="任务名称">
        <a-input v-model:value="formState.name" placeholder="请输入任务名称" />
      </a-form-item>
      <a-form-item label="任务描述">
        <a-input v-model:value="formState.desc" placeholder="请输入任务描述" />
      </a-form-item>
      <a-form-item label="流程组">
        <a-select v-model:value="formState.group" :options="groupOptions" placeholder="请选择流程组" />
      </a-form-item>
      <a-form-item label="目标数据源">
        <a-select v-model:value="formState.dbType" :options="dbTypeOptions" style="width:120px" placeholder="请选择类型" />
        <a-select v-model:value="formState.dbInstance" :options="dbInstanceOptions" style="width:180px;margin-left:8px;" placeholder="请选择实例" />
        <a-button type="link" @click="testConnection">连接测试</a-button>
      </a-form-item>
      <div style="margin-bottom: 16px;">
        <p style="font-weight: 500; margin-bottom: 8px">选择迁移范围：</p>
        <a-checkbox-group v-model:value="selectedRange" :options="selectedRangeOptions" />
      </div>
      <div style="margin-bottom: 16px;">
        <p style="font-weight: 500; margin-bottom: 8px">未选择迁移范围：</p>
        <a-checkbox-group v-model:value="unselectedRange" :options="unselectedRangeOptions" />
      </div>
    </a-form>
  </a-modal>
</template>

<script setup>
import { ref, reactive, watch, defineExpose, defineEmits } from 'vue';
import { message } from 'ant-design-vue';
import * as http from '@/api/flow/index.js';

const props = defineProps({
  record: { type: Object, default: () => ({}) },
});
const open = ref(false);
const formState = reactive({
  name: '',
  desc: '',
  group: null,
  dbType: '',
  dbInstance: '',
});
const selectedRange = ref([]);
const unselectedRange = ref([]);
const groupOptions = ref([]);
const dbTypeOptions = ref([]);
const dbInstanceOptions = ref([]);

// 获取所有流程组
function fetchAllGroups() {
  const params = { type: 'all' };
  http.getAllRelFlowGroupInfo(params).then(res => {
    const { code, data, msg } = res;
    if (code === "000000") {
      if (!data || !data.length) {
        message.warning(msg || '暂无流程组');
        groupOptions.value = [];
      } else {
        groupOptions.value = data.map(item => ({
          value: item.id,
          label: item.flow_group_name
        }));
      }
    } else {
      message.warning(msg || '获取流程组失败');
      groupOptions.value = [];
    }
  });
}

// 获取数据库类型
async function fetchDbTypes() {
  const params = { userID: window.sessionStorage.getItem("userId") };
  const res = await http.getDataBaseTypeInfo(params);
  if (res.code === "000000" && res.data) {
    dbTypeOptions.value = res.data.map(item => ({
      value: item.dbType,
      label: item.dbTypeName
    }));
  } else {
    dbTypeOptions.value = [];
    message.warning(res.msg || "获取数据库类型失败");
  }
}

// 获取数据库实例
async function fetchDbInstances(dbType) {
  const params = {
    userID: window.sessionStorage.getItem("userId"),
    dbType
  };
  const res = await http.getDataBaseInstanceInfo(params);
  if (res.code === "000000" && res.data) {
    dbInstanceOptions.value = res.data.map(item => ({
      value: item.dbConfId,
      label: item.dbConfNameShow || item.dbConfName
    }));
  } else {
    dbInstanceOptions.value = [];
    message.warning(res.msg || "获取数据库实例失败");
  }
}

// 弹窗打开时自动获取流程组和类型
watch(open, (val) => {
  if (val) {
    fetchAllGroups();
    fetchDbTypes();
    if (formState.dbType) fetchDbInstances(formState.dbType);
  }
});

// 选择类型时自动获取实例
watch(() => formState.dbType, (val) => {
  if (val) {
    fetchDbInstances(val);
  } else {
    dbInstanceOptions.value = [];
  }
});

// 回显功能
watch(
  () => props.record,
  (val) => {
    if (val) {
      formState.name = val.name || '';
      formState.desc = val.desc || '';
      formState.group = val.group || null;
      formState.dbType = val.dbType || '';
      formState.dbInstance = val.dbInstance || '';
      selectedRange.value = val.selectedRange || [];
      unselectedRange.value = val.unselectedRange || [];
    }
  },
  { immediate: true, deep: true }
);

const emit = defineEmits(['close']);
const closes = () => {
  open.value = false;
  emit('close');
};
const openDrawer = (record) => {
  open.value = true;
};
const testConnection = () => {
  // 连接测试逻辑
  alert('连接测试功能待实现');
};
const handleSubmit = () => {
  // 保存逻辑
  alert('保存功能待实现');
  closes();
};
defineExpose({ openDrawer, closes });
</script>